import 'package:cached_network_image/cached_network_image.dart';
import 'package:edu/constants/app_images.dart';
import 'package:edu/constants/config.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/app_preferences.dart';
import 'package:edu/utils/app_theme.dart';
import 'package:flutter/material.dart';

class AccountAvatarWidget extends StatefulWidget {
  const AccountAvatarWidget({super.key});

  @override
  State<AccountAvatarWidget> createState() => _AccountAvatarWidgetState();
}

class _AccountAvatarWidgetState extends State<AccountAvatarWidget> {
  int _index = 0; // 索引

  // 初始化
  @override
  void initState() {
    super.initState();
    AccountInfo.shared.avatarChangeIndexNotifier.addListener(_updateIndex);
  }

  // 销毁
  @override
  void dispose() {
    super.dispose();
    AccountInfo.shared.avatarChangeIndexNotifier.removeListener(_updateIndex);
  }

  // 更新索引-监听器回调方法
  void _updateIndex() {
    setState(() {
      // 实现 UI 与数据的同步
      _index = AccountInfo.shared.avatarChangeIndexNotifier.value;
    });
  }

  @override
  Widget build(BuildContext context) {
    return _InnerAccountUserAvatar(key: ValueKey(_index));
  }
}

/* 显示用户头像 */
class _InnerAccountUserAvatar extends StatelessWidget {
  const _InnerAccountUserAvatar({super.key});

  @override
  Widget build(BuildContext context) {
    final token = AppPreferences.shared.userToken;
    final avatar = AccountInfo.shared.userBrief?.avatar;

    // 如果 token 或 avatar 为空，直接显示本地占位图像（AppImages.avatarPlaceholder）
    // 否则使用 CachedNetworkImage 加载网络头像
    if (token == null || avatar == null) {
      return Image.asset(AppImages.avatarPlaceholder);
    }
    return CachedNetworkImage(
      imageUrl: '${Config.baseUrl}/v1/user/avatar',
      httpHeaders: {'authorization': 'Bearer $token'},
      placeholder: (context, url) => ColorFiltered(
        colorFilter: ColorFilter.mode(
          AppTheme.shared.currentTheme.colorScheme.primary,
          BlendMode.modulate,
        ),
        child: Image.asset(AppImages.avatarPlaceholder),
      ),
      fit: BoxFit.cover,
      errorWidget: (context, url, error) =>
          Image.asset(AppImages.avatarPlaceholder),
      errorListener: (e) {},
    );
  }
}
